<template>
  <div class="container">
    <div :style="{background: backgroundImage}" v-for="n in 12" :key="n" class="load-blur">
      <img src="../assets/image.jpeg" alt="" loading="lazy">
    </div>
  </div>
</template>

<script>
export default {
  name: "LazyImage",
  data() {
    return {
      image: require('../assets/image-small.jpeg')
    }
  },
  computed: {
    backgroundImage() {
      return `url(${this.image})`
    }
  },
  mounted() {
    const elements = document.querySelectorAll('.load-blur')
    elements.forEach(ele => {
      const image = ele.querySelector('img')

      const loaded = () => {
        ele.classList.add('loaded')
      }

      if (image.complete) {
        loaded()
      } else {
        image.addEventListener('load', loaded)
      }
    })
  }
}
</script>

<style scoped>
.container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

img {
  aspect-ratio: 1 / 1;
  width: 100%;
  display: block;
  object-fit: cover;
  object-position: center;
}

.load-blur {
  background-size: cover;
  background-position: center;
}

.load-blur.loaded > img {
  opacity: 1;
}

.load-blur > img {
  opacity: 0;
  transition: opacity 200ms ease-in-out;
}
</style>